package com.zj.core.activity

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import com.zj.core.base.BaseDrawerActivity
import com.zj.core.adapter.RecordRecycleAdapter
import android.support.v7.widget.LinearLayoutManager
import com.fileutils.StringUtils
import com.zj.core.base.BaseApplication.Companion.context
import kotlinx.android.synthetic.main.activity_main.*
import com.scwang.smartrefresh.layout.footer.ClassicsFooter
import com.scwang.smartrefresh.header.MaterialHeader
import com.dialogutils.ToastUtil
import com.fileutils.FileUtils
import com.fileutils.SPUtils
import com.google.gson.Gson
import com.moduleinterface.InterfaceFactory
import com.zj.core.net.NetPresenter
import com.systemutils.SystemUtil
import com.utils.DateUtils
import com.utils.DateUtils.DATE_FORMAT_4
import com.zj.core.base.BaseApplication
import com.zj.core.bean.NurseRecResBean
import com.zj.core.bean.UpdateBean
import com.zj.core.bean.UserInfo
import com.zj.core.bean.bean_output.QueryNurseInfoOutputBean
import com.zj.core.dialog.BindNurseNameDialog
import com.zj.core.dialog.NoteDialog
import com.zj.core.interfaces.TextMessageIml
import com.zj.core.interfaces.RecycleAdapterIml
import com.zj.core.net.NetValueCallBackIml
import com.zj.core.services.DownloadService
import com.zj.core.tools.Constant
import com.zj.core.tools.Constant.Companion.DETAIL_ADD_KEY
import com.zj.core.tools.Constant.Companion.DETAIL_ADD_STATUS
import com.zj.core.tools.Constant.Companion.REQUEST_RECORD_RES_KEY
import com.zj.core.tools.Constant.Companion.RESULT_RECORD_SKY
import com.zj.core.tools.Constant.Companion.UPDATE_MES_KEY
import org.jetbrains.anko.alert


/**
 * 主页Activity
 */
class MainActivity : BaseDrawerActivity(), RecycleAdapterIml {

    private var mBeanList: NurseRecResBean.DatEntity.RowsEntity? = null
    private var mRecordBeanList: MutableList<NurseRecResBean.DatEntity.RowsEntity>? = null
    private var mRecordAdapter: RecordRecycleAdapter? = null

    private var mAnnotationIndex: Int = 0        // 备注下标回调
    private var mOnRefush = true                 // 刷新状态
    private var mOnLoadMore = false              // 加载更多
    private var mSearchNurse = false             // 控制搜索状态
    private var mPageNum: Int = 1
    private var mLayoutManager: LinearLayoutManager? = null
    private var mBundle: Bundle? = null

    private var ScanActivityRequestCode = 1           //扫码后返回
    private var ScanActivityResultCode = 2

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        checkUpdate()

    }

    /**
     * 初始化控件
     */
    override fun initView() {
        super.initView()
        mBundle = Bundle()
        mRecordBeanList = NurseRecResBean.DatEntity().rows
        mBeanList = NurseRecResBean.DatEntity.RowsEntity()

        mLayoutManager = LinearLayoutManager(context)
        mLayoutManager?.orientation = LinearLayoutManager.VERTICAL

        mRecordAdapter = RecordRecycleAdapter(context, mRecordBeanList)
        mRecordAdapter?.setItemClickListener(this)
        detail_recycle_view.layoutManager = mLayoutManager
        detail_recycle_view.adapter = mRecordAdapter
        loadRefreshLayout()
    }

    /**
     * 初始化加载控件
     */
    private fun loadRefreshLayout() {
        refreshLayout.setRefreshHeader(MaterialHeader(context))
        refreshLayout.setRefreshFooter(ClassicsFooter(context))
        refreshLayout.setOnRefreshListener {
            mOnRefush = true
            mSearchNurse = false
            mPageNum = 1
            requestNurseList()
        }
        refreshLayout.setOnLoadMoreListener {
            mOnLoadMore = true
            if (mSearchNurse) {               //查询状态
                requestNurseList("", "", "")
            } else {                          //正常获取
                requestNurseList()
            }
        }
    }

    /**
     * 查询患者
     * startTime: 2019-11-26 06:00:00
     */
    override fun searchRecord(str: String) {
        if (str != "") {
            mOnRefush = true
            mSearchNurse = true
            mPageNum = 1

            if (str.contains("-")) {
                val timeArray = str.split("-")
                val time1 = DateUtils.dateFormat(0, timeArray[0], "").split("|")[0]
                val time2 = DateUtils.dateFormat(0, timeArray[1], "").split("|")[0]

                if (time1 != "" && DateUtils.isValidDate(time1, "HH:mm")
                    && time2 != "" && DateUtils.isValidDate(time2, "HH:mm")
                ) {

                    val data1 = DateUtils.getNowDateFormat(DATE_FORMAT_4) + " " + time1 + ":00"
                    val data2 = DateUtils.getNowDateFormat(DATE_FORMAT_4) + " " + time2 + ":00"
                    requestNurseList("", "", data1, data2)
                }
            } else {
                with(DateUtils.dateFormat(0, str, "")) {
                    if (this != "" && DateUtils.isValidDate(this, "HH:mm")) {
                        val data =
                            DateUtils.getNowDateFormat(DATE_FORMAT_4) + " " + this.split("|")[0] + ":00"
                        requestNurseList("", "", data)
                    } else {
                        requestNurseList(str, "", "")
                    }
                }
            }
        }
    }

    /**
     * 在获取到科室信息后
     * 请求历史数据
     * 且查询护士绑定信息
     */
    override fun requestNurseHis() {
        mOnRefush = true
        mSearchNurse = false
        mPageNum = 1
        requestNurseList()
        seachNurseBind()
    }

    /**
     * 操作记录接口
     */
    private var operationRecordIml = object : NetValueCallBackIml {
        override fun onNext(values: Any?, bean: Any?) {
            mRecordBeanList?.let {
                when {
                    mOnRefush -> {                        //如果正在刷新中，结束刷新
                        mOnRefush = false
                        it.clear()
                        it.addAll((values as NurseRecResBean).dat?.rows!!)
                        refreshLayout.finishRefresh()
                        mRecordAdapter?.onRefush(values.dat?.rows!!)
                    }
                    mOnLoadMore -> {                      //加载更多中
                        mOnLoadMore = false
                        it.addAll((values as NurseRecResBean).dat?.rows!!)
                        refreshLayout.finishLoadMore()
                        mRecordAdapter?.onLoadMore(values.dat?.rows!!)
                    }
                    else -> {
                        //mRecordAdapter.onRefush(record.getDat().getRows());
                    }
                }
            }
        }

        override fun onError() {
            if (stopRefush()) {
                ToastUtil.showShort(context, "刷新失败")
            }

            if (stopLoadMore()) {
                ToastUtil.showShort(context, "加载失败")
            }
        }

        override fun onSubscribe(data: Any?) {}
        override fun onComplete() {}
    }

    /**
     * 查询护士绑定
     */
    private fun seachNurseBind() {
        NetPresenter().queryNurseName(
            object : NetValueCallBackIml {
                override fun onComplete() {}
                override fun onSubscribe(data: Any?) {}
                @SuppressLint("SetTextI18n")
                override fun onNext(values: Any?, bean: Any?) {
                    val queryNurseBean: QueryNurseInfoOutputBean=Gson().fromJson(values as String, QueryNurseInfoOutputBean::class.java)
                    if (queryNurseBean.dat.rows.isEmpty()){
                        BindNurseNameDialog(
                            this@MainActivity,
                            "",
                            bindNurseNameIml
                        ).show()
                    }else{
                        val mNurseName=queryNurseBean.dat.rows[0].nursename
                        title_bar_tv.text = "当前护士:\n$mNurseName"
                        user_id_tv.text = mNurseName
                    }
                }

                override fun onError() {
                    ToastUtil.showShort(BaseApplication.context, "护士信息,查询失败")
                }
            },
            hospitalId,
            departmentId,
            nurseId,
            "0"
        )
    }

    /**
     * 请求数据
     */
    private fun requestNurseList(
        mes: String? = "",
        patientId: String? = "",
        startTime: String? = "",
        endTime: String? = ""
    ) {
        NetPresenter().getNurseOperationRecord(
            operationRecordIml,
            mHospitalID,
            mDepartmentID,
            mPageNum++,
            nurseId,
            patientId,
            mes,
            endTime,
            startTime
        )

    }

    /**
     * 版本更新
     */
    private fun checkUpdate() {
        NetPresenter().updateVersion(object : NetValueCallBackIml {
            override fun onSubscribe(data: Any?) {}
            override fun onComplete() {}
            override fun onError() {}
            override fun onNext(values: Any?, bean: Any?) {
                val versionCode = SystemUtil.getVersionCode(context)
                val mUpdateMes = values as List<UpdateBean.DatBean.RowsBean>
                if (mUpdateMes.isNotEmpty() && versionCode < mUpdateMes[0].versionnumber) {
                    val updateAlert = alert("有新版本发布，是否更新？", "提示") {
                        positiveButton("更新") {
                            DownloadService(context)
                                .setFileUrl(mUpdateMes[0].updateurl.toString())
                                .setFileSavePath(Constant.downloadPath)
                                .setFileSaveName("zj.apk")
                                .execute()
                        }
                    }
                    updateAlert.isCancelable = false
                    updateAlert.show()
                } else {
                    val updateMes = SPUtils.get(context, UPDATE_MES_KEY, 0)
                    if (updateMes == 0 || (updateMes as Int) < versionCode) {                 //提示更新内容
                        alert(FileUtils.initAssets(context), "当前版本更新内容：") {
                            positiveButton("已了解") {}
                        }.show()
                        SPUtils.put(context, UPDATE_MES_KEY, versionCode)
                    }
                }
            }
        })
    }


    /**
     * 备注提示框，内容回调后请求网络
     */
    private var noteChangeIml = object : TextMessageIml {
        override fun messageResult(str: String) {
            mChangeAnnoText(str)
        }
    }

    /**
     * 新增或修改备注（实现）
     */
    private fun mChangeAnnoText(mDialogText: String) {
        NetPresenter().addRemarkForOperation(
            object : NetValueCallBackIml {
                override fun onNext(values: Any?, bean: Any?) {
                    mRecordBeanList?.get(mAnnotationIndex)?.msg = mDialogText
                    mRecordAdapter?.onRefush(mRecordBeanList)
                }

                override fun onSubscribe(data: Any?) {}
                override fun onError() {}
                override fun onComplete() {}
            }, "" + mRecordBeanList?.get(mAnnotationIndex)?.id, mDialogText,
            mRecordBeanList?.get(mAnnotationIndex)?.patientid.toString(), mHospitalID, mDepartmentID
        )
    }

    /**
     * 添加护士姓名提示框，内容回调后请求网络
     */
    private var bindNurseNameIml = object : TextMessageIml {
        override fun messageResult(str: String) {
            NetPresenter().BindNurseInfo(
                object : NetValueCallBackIml {
                    override fun onNext(values: Any?, bean: Any?) {
                        ToastUtil.showShort(context, "护士姓名,绑定成功")
                        UserInfo.nurseName=str
                        title_bar_tv.text = "当前护士:\n$str"
                        user_id_tv.text = str
                    }

                    override fun onSubscribe(data: Any?) {}
                    override fun onError() {
                        ToastUtil.showShort(context, "护士姓名,绑定失败")
                    }
                    override fun onComplete() {}
                },
                hospitalId,
                departmentId,
                nurseId,
                str
            )
        }
    }

    /**
     * 贸人设备
     */
    override fun maorenClick() {
        centerClick()
    }

    /**
     * 中间按键
     */
    override fun centerClick() {
        mBeanList?.nurseid = nurseId
        InterfaceFactory.getInstance().getmInterfaceQR().scanQRcode(this, "患者", 2)
    }

    /**
     * 界面数据返回
     */
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        when (requestCode) {
            ScanActivityRequestCode -> {                                   //条码识别
                if (resultCode == ScanActivityResultCode) {                //条码识别返回
                    val code = data?.getStringExtra("barcode")
                    mBeanList?.patientid = StringUtils.replaceBlank(code)

                    val mBundle = Bundle()
                    mBundle.putInt(DETAIL_ADD_STATUS, 0)
                    mBundle.putSerializable(DETAIL_ADD_KEY, mBeanList)
                    activityJumpForResult(
                        context!!,
                        REQUEST_RECORD_RES_KEY,
                        RecordActivity().javaClass,
                        mBundle
                    )

                    /**
                     * MDDecoder解码单例，需要及时销毁
                     */
                    InterfaceFactory.getInstance().getmInterfaceQR().destroyQR()
                }
            }

            REQUEST_RECORD_RES_KEY -> {                                     //数据录入界面返回
                if (resultCode == RESULT_RECORD_SKY) {
                    mOnRefush = true
                    mPageNum = 1
                    requestNurseList()
                }
            }
        }
    }


    /**
     * 新增
     */
    override fun add(index: Int) {
        mBundle?.let {
            it.putInt(DETAIL_ADD_STATUS, 0)
            it.putSerializable(DETAIL_ADD_KEY, mRecordBeanList?.get(index))
            activityJumpForResult(context!!, REQUEST_RECORD_RES_KEY, RecordActivity().javaClass, it)
        }
    }

    /**
     * 详情
     */
    override fun info(mRecordBean: NurseRecResBean.DatEntity.RowsEntity, position: Int) {
        mBundle?.let {
            it.putSerializable(Constant.RECORD_DETAIL_KEY, mRecordBean)
            activityJumpForResult(
                context!!, REQUEST_RECORD_RES_KEY,
                RecordDetailActivity().javaClass, it
            )
        }
    }

    /**
     * 备注
     */
    override fun annotation(position: Int) {
        mAnnotationIndex = position
        NoteDialog(
            this@MainActivity,
            mRecordBeanList?.get(position)?.msg,
            noteChangeIml
        )
            .show()
    }

    /**
     * 停止刷新
     */
    private fun stopRefush(): Boolean {
        if (mOnRefush) {                        //如果正在刷新中，结束刷新
            mOnRefush = false
            refreshLayout.finishRefresh()
            return true
        }
        return false
    }

    /**
     * 停止加载更多
     *
     * @return
     */
    private fun stopLoadMore(): Boolean {
        if (mOnLoadMore) {                        //如果正在刷新中，结束刷新
            mOnLoadMore = false
            refreshLayout.finishLoadMore()
            return true
        }
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        mRecordAdapter?.clean()
        if (mRecordAdapter != null) {
            mRecordAdapter = null
        }

        mRecordBeanList?.clear()
        if (mRecordBeanList != null) {
            mRecordBeanList = null
        }

        if (mBeanList != null) {
            mBeanList = null
        }

        if (mLayoutManager != null) {
            mLayoutManager = null
        }
        if (mBundle != null) {
            mBundle = null
        }
    }
}